import { sysLogin } from '@/api/login'
import { sysProfile, sysUser } from '@/api/user'
import { setToken, getToken } from '@/utils/auth'
import asyncRoutes from '@/router/module/index'
import Router from '@/router'
import { constantRoutes, resetRouter } from '@/router/index'
const state = {
  token: getToken() || '',
  userInfo: []
}
const mutations = {
  setToken(state, arr) {
    state.token = arr
    setToken(arr)
  },
  setUserinfo(state, arr) {
    state.userInfo = arr
    console.log(state.userInfo, '用户模块')
  },
  logout() {
    this.commit('user/setToken', '')
    this.commit('user/setUserinfo', '')
    resetRouter()
  }
}
const actions = {
  async toLogin(store, form) {
    const res = await sysLogin(form)
    store.commit('setToken', res.data)
    // console.log(res)
  },
  async getUserInfo(store) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    // console.log(res2, '用户模块')
    store.commit('setUserinfo', Object.assign({}, res.data, res2.data))

    // 导入路由拼接
    const newArr = asyncRoutes.filter((item) => {
      return res.data.roles.menus.includes(item.meta.name)
    })
    Router.addRoutes([...newArr, { path: '*', redirect: '/404', hidden: true }])
    console.log('newArr', newArr)
    const routerArr = [
      ...constantRoutes,
      ...newArr,
      { path: '*', redirect: '/404', hidden: true }
    ]
    store.commit('router/setrouterList', routerArr, { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
